package com.swak.validator.process.impl;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.regex.Pattern;

import com.swak.Constants;
import com.swak.annotation.validate.Regex;
import com.swak.utils.Maps;
import com.swak.utils.StringUtils;
import com.swak.validator.process.AbstractProcessor;

/**
 * 正则表达式处理
 *
 * @author lifeng
 */
public class RegexProcessor extends AbstractProcessor {

	Map<String, Pattern> Patterns = Maps.newHashMap();

	/**
	 * 处理的类型
	 */
	@Override
	protected Class<?> processBy() {
		return Regex.class;
	}

	/**
	 * 为 null 判断
	 */
	@Override
	protected boolean doProcess(Annotation check, Object value, String group) {
		Regex regex = (Regex) check;
		if (!this.matchGroup(regex.groups(), group)) {
			return true;
		}
		if (value != null && value instanceof String) {
			Pattern pattern = Patterns.get(regex.value());
			if (pattern == null) {
				pattern = Pattern.compile(regex.value());
			}
			return pattern.matcher((String) value).matches();
		}
		return true;
	}

	/**
	 * 处理为空的异常消息
	 */
	@Override
	protected String processMessage(Annotation ann) {
		Regex regex = (Regex) ann;
		return StringUtils.defaultIfEmpty(regex.msg(), Constants.REGEX_ERROR_MSG);
	}
}